import { Controller } from 'egg';

class UserController extends Controller {
    /**
     * 处理后台登录
     * @returns {Promise<void>}
     */
    public async login() {
        const { ctx, ctx: { request } } = this;
        try {
            ctx.validate({
                admin_username: 'string',
                admin_password: 'string',
            }, request.body)
        } catch (e) {
            ctx.body = ctx.helper.responseErrorParam(e.errors[0].message);
            return;
        }
        const param = request.body;
        const returnData: any = await this.service.adminService.login(param.admin_username, param.admin_password);
        const token = ctx.helper.genUUID();
        await this.updateToken(returnData.admin_id, token);
        ctx.body = { code: 1, msg: '登录成功', data: { token, admin_username: returnData.admin_username } };
    }

    /**
     * 登录成功后刷新token值
     * @param {string} admin_id
     * @param {string} token
     * @returns {Promise<void>}
     */
    public async updateToken(admin_id: string, token: string) {
        await this.service.adminService.updateToken(admin_id, token);
    }
}

export default UserController;
